<?php

namespace app\api\model;

use addons\epay\library\Service;
use app\admin\model\Crontab;
use app\admin\model\user\Coupon;
use app\common\model\Shop;
use app\common\model\User;
use think\Db;
use think\Log;
use think\Model;
use Yansongda\Pay\Pay;


class Order extends Model
{





    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public $refund_reason = [
        '包装与描述不符',
        '少发货',
        '收货商品有污渍/破损',
        '卖家发错货',
        '商品质量问题',
        '其他',
    ];

    public function notify($out_trade_no)
    {
        $order = Order::get(['order_no'=>$out_trade_no]);
        if ($order->pay_status == 1){
            return  false;
        }
        $order->pay_status = 1;
        $order->pay_time = time();
        $order->order_status = 1;
        $order->order_status_name = '已付款';
        $res = $order->save();

        //订单自动完成时间(天)
        $order_auto_complete_time = \app\common\model\Config::get(['name'=>'order_auto_complete_time'])->value;
        $complete_time = time()+$order_auto_complete_time*86400;
        //添加定时任务
        $cron = new Crontab();
        $data = [
            'type'=>'url',
            'title'=>'订单自动完成,订单id:'.$order->id,
            'content'=>request()->domain().'/api/order/complete?id='.$order->id,
            'schedule'=>schedule($complete_time),
            'maximums'=>1,
            'begintime'=>time(),
            'endtime'=>$complete_time,
            'status'=>'normal'
        ];
        $cron->save($data);

        if ($order->coupon_id){
            $userCoupon = Coupon::get($order->coupon_id);
            //优惠券已使用
            if (!empty($userCoupon)) {
                $userCoupon->save(['is_used' => 2,'order_id'=>$order->id,'use_time'=>time()]);
            }
        }
        User::money(-$order->pay_money,$order->user_id,'订单付款',$order->id,$order->shop_id);
        Shop::money($order->pay_money,$order->shop_id,'订单消费',$order->id,$order->user_id);
        return $res;
    }

    public function backrefund($order_id,$refund_price)
    {
        $order = Order::get($order_id);
        if ($order->refund_status==2)throw new \Exception('已退款');
        Db::startTrans();
        try {
            $res = $this->refundoperate($order->order_no, 'wechat',$refund_price);
            if (!$res){
                Db::rollback();
                throw new \Exception('退款失败');
            }
            $order->refund_status = 2;
            $order->refund_action_time = time();
            $order->save();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function refundoperate($order_sn, $paytype, $payamount)
    {
        $config = Service::getConfig($paytype);
        try {
            //$order = Order::getByOrderSn($order_sn);

            $response = Pay::wechat($config)->refund([
                'type'          => 'miniapp',
                'out_trade_no'  => $order_sn,
                'out_refund_no' => time(),
                'total_fee'     => $payamount * 100,
                'refund_fee'    => $payamount * 100
            ]);

            if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
            }

        } catch (\Exception $e) {
            Log::write("[{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
            throw new \Exception("同步退款失败，失败原因：" . $e->getMessage());

        }

        return true;
    }
}
